package com.huai.jt1078.server;

import com.huai.jt1078.config.VideoConfig;
import com.huai.jt1078.entity.Session;
import com.huai.jt1078.handler.http.GeneralResponseWriter;
import com.huai.jt1078.handler.http.NettyHttpServerHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;


/**
 * @author xingkong
 * @program jt1078
 * @description http服务
 * @date 2021-09-08 20:27
 **/
@Slf4j
@Service
public class HttpServer {


    @Autowired
    VideoConfig videoConfig;
    private static EventLoopGroup bossGroup;
    private static EventLoopGroup workerGroup;

    private static final AttributeKey<Session> SESSION_KEY = AttributeKey.valueOf("session");

    public void start() throws Exception {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception
                    {
                        ch.pipeline().addLast(
                                new GeneralResponseWriter(),
                                new HttpResponseEncoder(),
                                new HttpRequestDecoder(),
                                new HttpObjectAggregator(1024 * 64),
                                new NettyHttpServerHandler()
                        );
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        int port =videoConfig.getHttpPort();// PropertiesUtil.getInt("server.http.port", 3333);
        ChannelFuture channelFuture = bootstrap.bind(InetAddress.getByName("0.0.0.0"), port).sync();

        log.info("启动netty,port:{}",port);
        // 优雅的关闭服务器
        Channel channel = channelFuture.channel();
        channel.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        });

    }

}
